#include "test.h"
#include "ui_test.h"


test::test(QTcpSocket *soc, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::test),
    socket(soc)
{
    ui->setupUi(this);
    connect(socket, &QTcpSocket::readyRead, this, &test::recv_que);

    // 创建一个滚动区域来容纳题目和选项
    QScrollArea *scrollArea = new QScrollArea(this);
    QWidget *scrollWidget = new QWidget();
    QVBoxLayout *scrollLayout = new QVBoxLayout(scrollWidget);
    scrollLayout->setContentsMargins(10, 10, 10, 10);
    scrollLayout->setSpacing(10);
    scrollWidget->setLayout(scrollLayout);
    scrollArea->setWidget(scrollWidget);
    scrollArea->setWidgetResizable(true);

    // 添加用户输入名字的组件
    QLabel *nameLabel = new QLabel("请输入您的名字:", this);
    nameLineEdit = new QLineEdit(this);
    scrollLayout->addWidget(nameLabel);
    scrollLayout->addWidget(nameLineEdit);

    // 添加提交按钮
    QPushButton *submitButton = new QPushButton("提交");
    scrollLayout->addWidget(submitButton);
    connect(submitButton, &QPushButton::clicked, this, &test::on_submitButton_clicked);

    // 将滚动区域设置为当前窗口的中心部件
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(scrollArea);
    setLayout(mainLayout);

    // 设置对象名称，以便在 recv_que 中找到
    scrollWidget->setObjectName("scrollWidget");
}

test::~test()
{
    delete ui;
}

bool test::get_surState()
{
    return sur_flag;
}

void test::recv_que()
{
    QByteArray data = socket->readAll();
    qDebug() << "Received data:" << data;

    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    QString strData = codec->toUnicode(data);

    QJsonDocument doc = QJsonDocument::fromJson(strData.toUtf8());
    if (!doc.isArray()) {
        qDebug() << "Invalid JSON data received";
        return;
    }

    QJsonArray jsonArray = doc.array();
    QVBoxLayout *scrollLayout = qobject_cast<QVBoxLayout*>(findChild<QWidget*>("scrollWidget")->layout());

    if (!scrollLayout) {
        qDebug() << "Failed to find layout for scrollWidget";
        return;
    }

    // 清除现有的题目和选项
    QLayoutItem *child;
    while ((child = scrollLayout->takeAt(0)) != nullptr) {
        delete child->widget();
        delete child;
    }

    // 重新添加用户输入名字的组件
    QLabel *nameLabel = new QLabel("请输入您的名字:", this);
    nameLineEdit = new QLineEdit(this);
    scrollLayout->addWidget(nameLabel);
    scrollLayout->addWidget(nameLineEdit);

    for (const QJsonValue &value : jsonArray) {
        if (!value.isObject()) {
            qDebug() << "Invalid JSON object in array";
            continue;
        }

        QJsonObject obj = value.toObject();
        QString questionText = obj["text"].toString();
        QJsonValue optionsValue = obj["options"];

        if (questionText.isEmpty()) {
            qDebug() << "Empty question text found";
            continue;
        }

        // 创建一个 QGroupBox 来容纳题目和选项
        QGroupBox *groupBox = new QGroupBox(questionText);
        QVBoxLayout *groupBoxLayout = new QVBoxLayout(groupBox);

        if (optionsValue.isArray()) {
            QJsonArray optionsArray = optionsValue.toArray();
            for (const QJsonValue &optionValue : optionsArray) {
                if (!optionValue.isString()) {
                    qDebug() << "Invalid option value found";
                    continue;
                }

                QString optionText = optionValue.toString();
                if (optionText.isEmpty()) {
                    qDebug() << "Empty option text found";
                    continue;
                }

                QRadioButton *radioButton = new QRadioButton(optionText);
                groupBoxLayout->addWidget(radioButton);

                // 记录选中的答案
                connect(radioButton, &QRadioButton::toggled, [this, radioButton, obj](bool checked) {
                    if (checked) {
                        selectedAnswers[obj["id"].toInt()] = radioButton;
                    } else {
                        selectedAnswers.remove(obj["id"].toInt());
                    }
                });

                qDebug() << "Created radio button with text:" << optionText;
            }
        } else if (optionsValue.isString()) {
            QString optionsString = optionsValue.toString();
            QStringList optionsList = optionsString.split("|");
            for (const QString &optionText : optionsList) {
                if (optionText.isEmpty()) {
                    qDebug() << "Empty option text found";
                    continue;
                }

                QRadioButton *radioButton = new QRadioButton(optionText);
                groupBoxLayout->addWidget(radioButton);

                // 记录选中的答案
                connect(radioButton, &QRadioButton::toggled, [this, radioButton, obj](bool checked) {
                    if (checked) {
                        selectedAnswers[obj["id"].toInt()] = radioButton;
                    } else {
                        selectedAnswers.remove(obj["id"].toInt());
                    }
                });

                qDebug() << "Created radio button with text:" << optionText;
            }
        } else {
            qDebug() << "Invalid options format found";
        }

        scrollLayout->addWidget(groupBox);
    }

    // 重新添加提交按钮
    QPushButton *submitButton = new QPushButton("提交", this);
    scrollLayout->addWidget(submitButton);
    connect(submitButton, &QPushButton::clicked, this, &test::on_submitButton_clicked);

    // 更新界面
    update();
}

void test::on_submitButton_clicked()
{
    QJsonObject submitData;
    QString clientName = nameLineEdit->text();
    if (clientName.isEmpty()) {
        QMessageBox::warning(this, "警告", "请输入您的名字！");
        return;
    }

    submitData["client_name"] = clientName;
    submitData["submit_time"] = QDateTime::currentDateTime().toString(Qt::ISODate);

    QJsonArray answersArray;
    for (auto it = selectedAnswers.begin(); it != selectedAnswers.end(); ++it) {
        QJsonObject answerObj;
        answerObj["question_id"] = it.key();
        answerObj["answer"] = it.value()->text();
        answersArray.append(answerObj);
    }

    submitData["answers"] = answersArray;

    QJsonDocument doc(submitData);
    QByteArray jsonData = doc.toJson();

    socket->write(jsonData);
    socket->flush();

    qDebug() << "Submitted data:" << jsonData;

    // 清除选中的答案
    selectedAnswers.clear();
    QMessageBox::information(this,"提交","提交成功");
    sur_flag = true;
    this->close();
}
